/*

* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Smart-Shop开源商城系统/ Java商城-首选电商平台系统 请务必保留此注释头信息
* |     开源地址: https://gitee.com/ningbo-qishan/gruul-mall
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     可正常分享和学习源码,未经授权 不可商用！
* |     商业版中台购买/开源版商业授权 联系技术客服
* |     官网:  https://www.73app.cn/
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Copyright (c) 2016-2999 宁波启山智软科技有限公司
* |     版权所有 ,侵权必究！
* ------------------------------------------------------------------------

*/
package com.medusa.gruul.multi.client.account.service.service.impl;

import cn.hutool.core.util.StrUtil;
import com.medusa.gruul.common.core.auth.client.helper.ISecurity;
import com.medusa.gruul.common.core.auth.model.User;
import com.medusa.gruul.common.core.auth.model.UserExtends;
import com.medusa.gruul.common.core.auth.model.enums.AuthPlatform;
import com.medusa.gruul.common.core.auth.model.enums.Gender;
import com.medusa.gruul.common.core.auth.model.enums.WechatAuthType;
import com.medusa.gruul.common.core.constant.enums.AuthCodeEnum;
import com.medusa.gruul.common.core.exception.ServiceException;
import com.medusa.gruul.common.core.helper.AccessToken;
import com.medusa.gruul.common.core.helper.ISecurityUserService;
import com.medusa.gruul.common.core.util.SystemCode;
import com.medusa.gruul.multi.client.account.api.entity.MultiClientAccount;
import com.medusa.gruul.multi.client.account.api.entity.MultiClientAccountData;
import com.medusa.gruul.multi.client.account.api.entity.MultiClientAccountWechat;
import com.medusa.gruul.multi.client.account.api.model.dto.AccountDataUpdateDTO;
import com.medusa.gruul.multi.client.account.api.model.dto.MobileEncryptDataDTO;
import com.medusa.gruul.multi.client.account.service.feign.PlatformFeignClient;
import com.medusa.gruul.multi.client.account.service.helper.UserHelper;
import com.medusa.gruul.multi.client.account.service.mp.service.IMultiClientAccountDataService;
import com.medusa.gruul.multi.client.account.service.mp.service.IMultiClientAccountService;
import com.medusa.gruul.multi.client.account.service.mp.service.IMultiClientAccountWechatService;
import com.medusa.gruul.multi.client.account.service.service.AccountDataService;
import com.medusa.gruul.multi.client.account.service.service.AccountService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author 张治保
 * date 2021/12/6
 */
@Service
@RequiredArgsConstructor
public class AccountServiceImpl implements AccountService {

    private final IMultiClientAccountDataService multiClientAccountDataService;
    private final IMultiClientAccountService multiClientAccountService;
    private final IMultiClientAccountWechatService multiClientAccountWechatService;
    private final PlatformFeignClient platformFeignClient;
    private final AccountDataService accountDataService;
    private final ISecurityUserService securityUserService;
    private final static String CDN_TEMPLATE = "https://oss-tencent.bgniao.cn/head_portrait%20/images%20({}).png";

    @Override
    public AccessToken updateUserInfo(AccountDataUpdateDTO accountUpdate, AuthPlatform loginType) {
        User user = ISecurity.user().must();
        MultiClientAccountData data = multiClientAccountDataService.lambdaQuery().eq(
                MultiClientAccountData::getAccountId, user.getId()
        ).one();
        if (data == null) {
            throw new ServiceException(SystemCode.DATA_UPDATE_FAILED);
        }
        /*
         * 更新值
         */
        if (accountUpdate.getAvatar() != -1) {
            data.setAvatar(StrUtil.format(CDN_TEMPLATE, accountUpdate.getAvatar() + 1));
        }
        data.setNickname(accountUpdate.getNickname())
                .setGender(accountUpdate.getGender() == null ? Gender.UNKNOWN : accountUpdate.getGender())
                .setLanguage(accountUpdate.getLanguage());
        boolean success = multiClientAccountDataService.updateById(data);
        if (!success) {
            throw new ServiceException(SystemCode.DATA_UPDATE_FAILED);
        }
        /*
         * 更新修改时间缓存
         */
        ISecurity.updateModifyTimeCache(user.getUserId());

        MultiClientAccount account = multiClientAccountService.getAccountById(user.getId());
        UserExtends userExtends = null;
        if (loginType == AuthPlatform.WECHAT_MINI_APP) {
            userExtends = new UserExtends(
                    multiClientAccountWechatService.lambdaQuery()
                            .eq(MultiClientAccountWechat::getAccountId, user.getId())
                            .eq(MultiClientAccountWechat::getAuthType, WechatAuthType.WECHAT_MINI_APP)
                            .one()
            );
        } else {
            userExtends = new UserExtends();
        }

        AccessToken token = UserHelper.getTokenByAccount(account, userExtends);
        if (token == null) {
            throw new ServiceException(AuthCodeEnum.AUTH_REFRESH_FAIL.getDescription(), AuthCodeEnum.AUTH_REFRESH_FAIL.getType());
        }
        return token;
    }

    @Override
    public void updateWechatMobile(MobileEncryptDataDTO encryptData) {
        String mobile = platformFeignClient.decryptMobile(encryptData).successData();
        if (StrUtil.isBlank(mobile)) {
            throw new ServiceException(SystemCode.DATA_UPDATE_FAILED);
        }
        User user = ISecurity.user().must();
        boolean success = multiClientAccountService.lambdaUpdate()
                .set(MultiClientAccount::getMobile, mobile)
                .eq(MultiClientAccount::getId, user.getId())
                .update();
        if (!success) {
            throw new ServiceException(SystemCode.DATA_UPDATE_FAILED);
        }
        /*
         * 根据手机号同步用户数据
         */
        accountDataService.syncAccountExtendsByMobile(mobile);
        /*
         * 更新修改时间缓存
         */
        ISecurity.updateModifyTimeCache(user.getUserId());
    }

    @Override
    public List<String> availableAvatars() {
        return IntStream.range(1, 13)
                .mapToObj(
                        index -> StrUtil.format(CDN_TEMPLATE, index)
                ).collect(Collectors.toList());
    }

}
